package com.xydtech.ecard.ecard.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xydtech.ecard.ecard.service.IEcardLoanCalculatorService;
import com.xydtech.system.domain.SysLoanConfiguration;
import com.xydtech.system.mapper.SysLoanConfigurationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * <dd>描述: ~ 电子名片-贷款额度测算ServiceI业务层处理</dd>
 * <dd>创建时间：  13:47 2024/1/18</dd>
 * <dd>创建人： yuzhiguo</dd>
 * <dt>版本历史: </dt>
 * Date         Author         Version     Description
 * ------------------------------------------------------------------
 * 2024/1/18     yuzhiguo         1.0        1.0 Version
 */
@Service
public class EcardLoanCalculatorServiceImpl implements IEcardLoanCalculatorService {

    @Autowired
    private SysLoanConfigurationMapper sysLoanConfigurationMapper;

    /**
     * 贷款额度计算
     * @param jsonObject
     * @param deptId
     * @return
     */
    @Override
    public Double loanLimitCalculation(JSONObject jsonObject, Long deptId) {
        BigDecimal finalQuota = new BigDecimal(0);//最终结果
        BigDecimal familyAssets = new BigDecimal(0);//家庭资产
        BigDecimal familyLiabilities = new BigDecimal(0);//家庭负债
        BigDecimal monthlyIncome = new BigDecimal(0);//月收入
        BigDecimal monthlyRevenue = new BigDecimal(0);//月营业额
        try {
            //不同商户类型计算规则不同
            String merchantType = String.valueOf(jsonObject.get("merchantType"));//商户类型，1：个人/新市民；2：个体工商户
            if ("1".equals(merchantType)){//个人/新市民
                SysLoanConfiguration sysLoanConfiguration = sysLoanConfigurationMapper.selectLoanConfigurationByMerchantType(merchantType, String.valueOf(deptId));
                familyAssets = new BigDecimal(String.valueOf(jsonObject.get("familyAssets")));//家庭资产
                familyLiabilities = new BigDecimal(String.valueOf(jsonObject.get("familyLiabilities")));//家庭负债
                monthlyIncome = new BigDecimal(String.valueOf(jsonObject.get("monthlyIncome")));//月收入
                int personalAge = Integer.parseInt(String.valueOf(jsonObject.get("personalAge"))) ;//年龄
                String isSocialSecurity = String.valueOf(jsonObject.get("isSocialSecurity"));//是否缴纳社保，0：是，1：否
                String isAccumulationFund = String.valueOf(jsonObject.get("isAccumulationFund"));//是否缴纳公积金，0：是，1：否
                //第一步：A：（家庭资产-家庭负债）*70%
                BigDecimal finalQuotaA = (familyAssets.subtract(familyLiabilities)).multiply(new BigDecimal(sysLoanConfiguration.getAssetsLiabilitiesIndicator()));
                //第二步：B：月收入*12*60%*5
                BigDecimal finalQuotaB = monthlyIncome.multiply(new BigDecimal(sysLoanConfiguration.getMonthlyIncomeIndicator()));
                //第三步：C：A或B的最小值
                BigDecimal finalQuotaC = finalQuotaA.min(finalQuotaB);
                //第四步：D：根据年龄计算
                BigDecimal finalQuotaD = new BigDecimal(0);
                //小于20岁：取0
                if (personalAge < 20){
                    finalQuotaD = finalQuotaC.multiply(new BigDecimal(sysLoanConfiguration.getPersonalAgeaIndicator()));
                }
                //大于等于20岁且小于30岁：取C
                if ((personalAge >= 20 && personalAge < 30)){
                    finalQuotaD = finalQuotaC.multiply(new BigDecimal(sysLoanConfiguration.getPersonalAgebIndicator()));
                }
                //大于等于30岁且小于等于45岁：C*110%
                if (personalAge >= 30 && personalAge <= 45){
                    finalQuotaD = finalQuotaC.multiply(new BigDecimal(sysLoanConfiguration.getPersonalAgecIndicator()));
                }
                //大于45岁且小于等于55岁：取C
                if (personalAge > 45 && personalAge <= 55){
                    finalQuotaD = finalQuotaC.multiply(new BigDecimal(sysLoanConfiguration.getPersonalAgedIndicator()));;
                }
                //大于55岁且小于等于60岁：C*90%
                if (personalAge > 55 && personalAge <= 60){
                    finalQuotaD = finalQuotaC.multiply(new BigDecimal(sysLoanConfiguration.getPersonalAgeeIndicator()));
                }
                //大于60岁：取0
                if (personalAge > 60){
                    finalQuotaD = finalQuotaC.multiply(new BigDecimal(sysLoanConfiguration.getPersonalAgefIndicator()));;
                }
                //如果第四步计算结果finalQuotaD为0了,直接赋值给最终额度，无需往下计算
                if (finalQuotaD.signum() == 0){
                    finalQuota = finalQuotaD;
                } else {
                    //第五步：E：是否缴纳社保：0：是：D*110%，1：否：取D
                    BigDecimal finalQuotaE = new BigDecimal(0);
                    if ("0".equals(isSocialSecurity)){
                        finalQuotaE = finalQuotaD.multiply(new BigDecimal(sysLoanConfiguration.getIstrueSocialSecurity()));
                    }else if ("1".equals(isSocialSecurity)){
                        finalQuotaE = finalQuotaD.multiply(new BigDecimal(sysLoanConfiguration.getIsfalseSocialSecurity()));;
                    }
                    //第六步：F：是否缴纳公积金：0：是：E*110%，1：否：取E
                    BigDecimal finalQuotaF = new BigDecimal(0);
                    if ("0".equals(isAccumulationFund)){
                        finalQuotaF = finalQuotaE.multiply(new BigDecimal(sysLoanConfiguration.getIstrueAccumulationFund()));
                    }else if ("1".equals(isAccumulationFund)){
                        finalQuotaF = finalQuotaE.multiply(new BigDecimal(sysLoanConfiguration.getIsfalseAccumulationFund()));;
                    }
                    finalQuota = finalQuotaF;
                }
            }else if ("2".equals(merchantType)){//个体工商户
                SysLoanConfiguration sysLoanConfiguration = sysLoanConfigurationMapper.selectLoanConfigurationByMerchantType(merchantType, String.valueOf(deptId));
                familyAssets = new BigDecimal(String.valueOf(jsonObject.get("familyAssets")));//家庭资产
                familyLiabilities = new BigDecimal(String.valueOf(jsonObject.get("familyLiabilities")));//家庭负债
                monthlyRevenue = new BigDecimal(String.valueOf(jsonObject.get("monthlyRevenue")));//月营业额
                //第一步：A：（家庭资产-家庭负债）*70%
                BigDecimal finalQuotaA = (familyAssets.subtract(familyLiabilities)).multiply(new BigDecimal(sysLoanConfiguration.getAssetsLiabilitiesIndicator()));
                //第二步：B：月营业额*30%*12*60%*5
                BigDecimal finalQuotaB = monthlyRevenue.multiply(new BigDecimal(sysLoanConfiguration.getMonthlyRevenueIndicator()));
                //第三步：C：A或B的最小值
                BigDecimal finalQuotaC = finalQuotaA.min(finalQuotaB);
                finalQuota = finalQuotaC;
            }
        }catch (Exception e){
            System.out.println("loanLimitCalculation = " + e);
        }
        //最终额度，保留到千位（四舍五入）
        Double finalLimit = halfAdjust(finalQuota.doubleValue() /1000) * 1000;
        //第一步时（家庭资产-家庭负债）如果小于0，则最终额度为0
        if (finalLimit < 0){
            finalLimit = 0.0;
        }
        return finalLimit;
    }

    /**
     * 四舍五入，保留2位小数
     * @param num
     * @return
     */
    private static double halfAdjust(double num){
        BigDecimal numBig = new BigDecimal(num);
        return numBig.setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}
